package com.xiaoma.test.factorial;

/**
 * @author maj
 * @ClassName BigMath
 * @Description
 * @date 2020-08-05 16:22
 */
public class BigMath {

  /*
   * 功能描述:
       阶乘的结果放在数组，十进制的每一位对应数组的每个元素，
       * 然后乘以新的数，结果放在原来的位置，完成进位后就是新的数组
   */

  public static void main(String[] args) {
    int n=7665;
    int count=26449;
    long begin = System.currentTimeMillis();
    System.out.println(Math.log10(n));
    String result =  factorial(n,count);
    long end = System.currentTimeMillis();
    System.out.println("耗时:"+(end-begin)+"毫秒");
    System.out.println(result);
  }

  private static String factorial(int n, int maxSize) {
    int res[] = new int[maxSize];
    res[0] = 1; //从1开始乘
    int resSize = 1;//当前结果已经有多少位
    //n为26449，结果有多少位，就要乘多少次
    for (int x = 2; x <= n; x++) {
//      resSize = multiply(x, res, resSize);
      int carry = 0;

      for (int i = 0; i < resSize; i++) {
        //阶乘结果数组的每个元素都乘以新的数
        int prod = res[i] * x + carry;
        res[i] = prod % 10;
        carry = prod / 10;
      }


      //for遍历完后，判断最后进位是否继续进位
      while (carry != 0) {
        res[resSize] = carry % 10;
        carry = carry / 10;
        resSize++;
      }

    }

    StringBuffer buff = new StringBuffer();
    for (int i = resSize - 1; i >= 0; i--) {
      buff.append(res[i]);
    }

    return buff.toString();
  }


  private static int multiply(int x, int res[], int resSize) {

    int carry = 0;

    for (int i = 0; i < resSize; i++) {
      //阶乘结果数组的每个元素都乘以新的数
      int prod = res[i] * x + carry;
      res[i] = prod % 10;
      carry = prod / 10;
    }


    while (carry != 0) {
      res[resSize] = carry % 10;
      carry = carry / 10;
      resSize++;
    }

    return resSize;
  }


  /* public static void main(String[] args) {
    int n = 7665;
    double sum = 0, digit;

    for (int a = 1; a <= n; a++)//计算阶乘位数
    {
      sum += Math.log10(a);
    }
    digit = (int) sum + 1;
    System.out.println(digit);

   int timeBegin = (int) System.currentTimeMillis();

    String factorial = factorial(n);

    int timeFinishi = (int) System.currentTimeMillis();
    int time = timeFinishi - timeBegin;

    System.out.println(factorial);
    System.out.println(time);

  }*/


}
